<script setup>
	import { ref } from 'vue'
	import { ElNotification } from 'element-plus'
	import { Plus } from '@element-plus/icons-vue'
	import { useRoleStore } from '@/stores/role'
	import { useTokenStore } from '@/stores/token'
	import { Upload } from '@element-plus/icons-vue'
	import { updateAvatarService } from '@/api/user'

	const tokenStore = useTokenStore()
	const userStore = useRoleStore()
	const imageUrl = ref(userStore.info.userAvatar)

	const uploadSuccess = (result) => {
		imageUrl.value = result.data
	}
	const updateAvatar = async () => {
		let result = await updateAvatarService(imageUrl.value)
		ElNotification({
			title: '修改成功',
			message: `成功修改头像`,
			type: 'success',
		})
		userStore.info.userAvatar = imageUrl.value
	}
</script>

<template>
	<el-card>
		<template #header>更换头像</template>
		<el-upload
			class="avatar-uploader"
			action="/api/user/avatar"
			:headers="{ Authorization: tokenStore.token }"
			:on-success="uploadSuccess"
			:show-file-list="false"
			:auto-upload="true">
			<img v-if="imageUrl" :src="imageUrl" class="avatar" />
			<el-icon v-else class="avatar-uploader-icon">
				<Plus />
			</el-icon>
		</el-upload>
		<el-button type="success" :icon="Upload" @click="updateAvatar"
			>确认更换</el-button
		>
	</el-card>
</template>

<style scoped>
	.avatar-uploader .avatar {
		width: 178px;
		height: 178px;
		display: block;
	}
	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}
</style>
